package com.difsonapps.android.marker.dialogs;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.IRefresher;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.beans.PhotoUpload;
import com.difsonapps.android.marker.beans.Video;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class EditPhotoDialog extends Dialog{
	Activity activity;
	Photo photo;
	IRefresher<Photo> refresher;
	Video video;
	IRefresher<Video> videoRefresher;
	
	
	EditText nameEditText;
	EditText descriptionEditText;
	
	public EditPhotoDialog(Activity activity, Photo photo, IRefresher<Photo> refresher) {
		super(activity);
		this.activity = activity;
		setTitle(R.string.editing_photo);
		this.photo = photo;
		this.refresher = refresher;
		
		setContentView(R.layout.dialog_edit_photo);
		nameEditText = (EditText)findViewById(R.id.name_text);
		descriptionEditText = (EditText)findViewById(R.id.description_text);
		findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				save();
			}
		});
		findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelAction();
			}
		});
		
		if(photo!=null){
			nameEditText.setText(photo.getTitle());
			descriptionEditText.setText(photo.getDescription());
		}
	}
	public EditPhotoDialog(Activity activity, Video video, IRefresher<Video> videoRefresher) {
		super(activity);
		this.activity = activity;
		setTitle(R.string.editing_video);
		this.video = video;
		this.videoRefresher = videoRefresher;
		
		setContentView(R.layout.dialog_edit_photo);
		nameEditText = (EditText)findViewById(R.id.name_text);
		descriptionEditText = (EditText)findViewById(R.id.description_text);
		findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				save();
			}
		});
		findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelAction();
			}
		});
		
		if(video!=null){
			nameEditText.setText(video.getName());
			descriptionEditText.setText(video.getDescription());
		}
	}
	
	private void save(){
		updatePhoto();
	}
	
	private void cancelAction(){
		dismiss();
	}
	
	ProgressDialog loadingProgressDialog;
	
	private void updatePhoto(){
		if(photo==null && video==null) return;
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", ""+(photo!=null?photo.getId():video.getId()));
		params.put("name", nameEditText.getText().toString());
		params.put("description", descriptionEditText.getText().toString());
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				photo!=null?AppConstant.editphotoUrl:AppConstant.editvideoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	//hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonUpdatePhoto(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
       loadingProgressDialog = ProgressDialog.show(activity, activity.getResources().getString(R.string.loading), activity.getResources().getString(R.string.saving), true);
       loadingProgressDialog.setCancelable(true);
	}
	/**
	 * Parse the result of upload of an photo
	 * If it's the first photo, get the photo
	 * Upload the next photo if
	 */
	private void parseJsonUpdatePhoto(JSONObject response){
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
		try {
        	//toast(response.toString());
            if(response.has("success")&&(response.has("photo") || response.has("video"))){
            	String success = response.getString("success");
            	toast(success);
            	if(photo!=null){
	            	Photo newPhoto = Photo.parseFromJsonObject(response.getJSONObject("photo"));
	            	if(newPhoto!=null) {
	            		if(refresher!=null) refresher.refresh(newPhoto);
	            		dismiss();
	            	}
            	}else if(video!=null){
            		Video newVideo = Video.parseFromJsonObject(response.getJSONObject("video"));
	            	if(newVideo!=null) {
	            		if(videoRefresher!=null) videoRefresher.refresh(newVideo);
	            		dismiss();
	            	}
            	}
            	return;
            }else if(response.has("error")){
            	String error = response.getString("error");
            	toast(error);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
	}

	private void toast(String text){
		Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
	}

}
